package logic

import (
	"context"
	"fmt"
	"models"
	"pkg"

	"shop_srv/internal/svc"
	"shop_srv/shop_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type RestLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RestLogic {
	return &RestLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RestLogic) Rest(in *shop_srv.RestRequest) (*shop_srv.RestResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("SmsCaptcha:%s", in.Phone)
	code, _ := models.RDB.Get(models.Ctx, key).Result()
	if code != in.Code {
		return nil, fmt.Errorf("验证码错误")
	}
	var user models.User
	if err := models.DB.Where("user_phone = ?", in.Phone).Find(&user).Limit(1).Error; err != nil {
		return nil, err
	}
	if user.ID != 0 {
		return nil, fmt.Errorf("该手机号已被注册")
	}
	user = models.User{
		UserEMail:    in.EMail,
		UserPhone:    in.Phone,
		UserPassword: pkg.MD5(in.Password),
	}
	if err := models.DB.Create(&user).Error; err != nil {
		return nil, err
	}
	return &shop_srv.RestResponse{}, nil
}
